package com.tupi.project.http.component;


import com.tupi.project.util.LogUtil;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;


public class FileResponseBody extends ResponseBody
{
    private static final String TAG = FileResponseBody.class.getSimpleName();

    Response originalResponse;

    public FileResponseBody(Response originalResponse)
    {
        this.originalResponse = originalResponse;
    }

    @Override
    public MediaType contentType()
    {
        return originalResponse.body().contentType();
    }

    @Override
    public long contentLength()
    {
        LogUtil.e(TAG, "contentLength:   " + originalResponse.body().contentLength());
        return originalResponse.body().contentLength();
    }

    @Override
    public BufferedSource source()
    {
        return Okio.buffer(new ForwardingSource(originalResponse.body().source())
        {
            long bytesReaded = 0;
            int position=0;
            long contentLength=contentLength();

            @Override
            public long read(Buffer sink, long byteCount) throws IOException
            {
                long bytesRead = super.read(sink, byteCount);
                bytesReaded += bytesRead == -1 ? 0 : bytesRead;
                position= (int) (((float)bytesReaded/(float)contentLength)*100);
                // TODO: 2017/11/1
                LogUtil.e(TAG, "read:   " + bytesReaded + "  " + contentLength + "  " +
                        contentLength() + "   " + bytesRead / contentLength * 100);
//
//                EventBus.getDefault().post(new UploadEvent(TAG, position));
                return bytesRead;
            }
        });
    }
}
